package com.hmall.serch.service.impl;

import com.alibaba.fastjson.JSON;

import com.hmall.common.dto.PageDTO;
import com.hmall.serch.pojo.ItemDoc;
import com.hmall.serch.pojo.RequestParams;
import com.hmall.serch.service.ISearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SearchService implements ISearchService {
    @Autowired
    RestHighLevelClient client;

    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            buildBasicQuery(params, request);
            // 2.2.分页
            int page = params.getPage();
            int size = params.getSize();

            if("price".equals(params.getSortBy())){request.source().sort("price", SortOrder.ASC);}
            request.source().from((page - 1) * size).size(size);


            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));


            // 3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        String key = params.getKey();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }

        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        // 4.品牌条件
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 6.价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice())
            );
        }
        // 7.放入source
        request.source().query(boolQuery);
    }

    // 结果解析
    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<ItemDoc> items = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            itemDoc.setPrice(itemDoc.getPrice()*100);
            //获取高亮效果
            Map<String,HighlightField> highlightFiels =hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFiels)){
                HighlightField highlightField = highlightFiels.get("name");
                if (highlightField !=null){
                    String name = highlightField.getFragments()[0].string();
                    itemDoc.setName(name);
                }

            }
            // 放入集合
            items.add(itemDoc);
        }
        // 4.4.封装返回
        return new PageDTO<ItemDoc>(total, items);
    }


    }


